package ilincar.systemcore.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.TypedValue;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/***
 * 公用工具类
 * @author fanjunchen
 *
 */
public class CommonUtils {

    /***
     * json to object&lt;T&gt;
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> T getObject(String jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }


    public static <T> String toGson(T cls) {
        String t = null;
        try {
            Gson gson = new Gson();
            t = gson.toJson(cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /***
     * json to List&lt;T&gt;
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> List<T> getObjects(String jsonString, Class<T[]> cls) {
        List<T> list = null;
        try {
                                             /*Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<T>>() {}.getType());*/
            list = stringToArray(jsonString, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
        T[] arr = new Gson().fromJson(s, clazz);
        return Arrays.asList(arr);
    }

    /***
     * json to List<Map<String, Object>>
     * @param jsonString
     * @return
     */
    public static List<Map<String, Object>> listKeyMaps(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString,
                    new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /***
     * 获取某资源ID
     * @param ctx
     * @param type 资源类型 eg: string, drawable, layout
     * @param strId
     * @return
     */
    public static int getResourceId(Context ctx, String type, String strId) {
        try {
            return ctx.getResources().getIdentifier(strId, type,
                    ctx.getPackageName());
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /***
     * 跳转致发短信界面
     * @param ctx
     * @param num
     */
    public static void jumpToSms(Context ctx, String num) {
        Intent intent = new Intent();
        //系统默认的action，用来打开默认的短信界面
        intent.setAction(Intent.ACTION_SENDTO);
        //需要发短息的号码
        intent.setData(Uri.parse("smsto:" + num));
        ctx.startActivity(intent);
    }

    /***
     * 跳转致拨号界面
     * @param ctx
     * @param num
     */
    public static void jumpToPhone(Context ctx, String num) {
        Intent intent = new Intent();
        //系统默认的action，用来打开默认的拨号界面
        intent.setAction(Intent.ACTION_DIAL);// ACTION_CALL
        //需要发短息的号码
        intent.setData(Uri.parse("tel:" + num));
        ctx.startActivity(intent);
    }

    /***
     * 跳转致发短信界面
     * @param ctx
     * @param num
     */
    public static void jumpToSms(Activity ctx, String num, int enterAnim) {
        Intent intent = new Intent();
        //系统默认的action，用来打开默认的短信界面
        intent.setAction(Intent.ACTION_SENDTO);
        //需要发短息的号码
        intent.setData(Uri.parse("smsto:" + num));
        ctx.startActivity(intent);
        ctx.overridePendingTransition(enterAnim, 0);
    }

    /***
     * 跳转致打电话界面
     * @param ctx
     * @param num
     */
    public static void jumpToCallPhone(Activity ctx, String num, int enterAnim) {
        Intent intent = new Intent();
        //系统默认的action，用来打开默认的打电话界面
        intent.setAction(Intent.ACTION_CALL);// ACTION_CALL
        //需要发短息的号码
        intent.setData(Uri.parse("tel:" + num));
        ctx.startActivity(intent);
        ctx.overridePendingTransition(enterAnim, 0);
    }

    /***
     * 跳转致某个联系人界面
     * @param ctx
     * @param num
     */
    public static void jumpToPeople(Activity ctx, String num, int enterAnim) {
        Intent intent = new Intent();
        //系统默认的action，用来打开默认的短信界面
        intent.setAction(Intent.ACTION_VIEW);// ACTION_CALL
        //需要发短息的号码
        intent.setData(Uri.parse("tel:" + num));
        ctx.startActivity(intent);
        ctx.overridePendingTransition(enterAnim, 0);
    }

    /**
     * 全角转化为半角的方法
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (isChinese(c[i])) {
                if (c[i] == 12288) {
                    c[i] = (char) 32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    /***
     * 判断一个字符是否为中文
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }


    /***
     * 解密
     * @param response
     * @return
     */
    public static String decodeAndUnGzip(String response) throws IOException {
        response = URLDecoder.decode(response, "UTF-8");
        return response;
    }

    /***
     * 加密操作
     * @param json
     * @return
     * @throws IOException
     */
    public static String encodeAndGzip(String json) throws IOException {
        json = URLEncoder.encode(json, "UTF-8");
        return json;
    }

    public static int dp2px(Context context, float dpValue) {
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources()
                .getDisplayMetrics()) + 0.5);
    }

    public static int sp2px(Context context, float spValue) {
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources()
                .getDisplayMetrics()) + 0.5);
    }

    /**
     * 获取imei号即设备号
     *
     * @param context
     * @return
     */
    public static String getImei(Context context) {
        TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = manager.getDeviceId();
        if (imei == null) {
            imei = "";
        }
        return imei;
    }

    /**
     * 获取SN
     *
     * @param context
     * @return
     */
    public static String getSN(Context context) {
        TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String sn = manager.getSimSerialNumber();
        if (sn == null) {
            sn = "";
        }
        return sn;
    }

    public static String getLocalMacAddress(Context ctx) {
        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String mac = info.getMacAddress();
        if (mac == null)
            return "";
        mac = mac.replace(":", "");
        mac = String.valueOf(Long.parseLong(mac, 16));
        return mac;
    }

    /***
     * 打开WIFI
     * @param ctx
     */
    public static boolean openWifi(Context ctx) {
        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        boolean isOk = false;
        if (wifi != null && !(isOk = wifi.isWifiEnabled())) {
            wifi.setWifiEnabled(true);
        }
        return isOk;
    }

    /***
     * 关闭WIFI
     * @param ctx
     */
    public static void closeWifi(Context ctx, boolean isEnable) {
        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        if (wifi != null && wifi.isWifiEnabled() != isEnable) {
            wifi.setWifiEnabled(isEnable);
        }
    }

    public static String getModel(Context context) {
        return Build.MODEL;
    }

    /**
     * 获取版本名称
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取渠道号
     *
     * @param context
     * @return
     */
    public static String getChannel(Context context) {
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return info.metaData.getString("UMENG_CHANNEL", "hame"); //这个是友盟的键值
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "hame";
        }
    }

    /***
     * 获取版本号
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /***
     * 读取文件成String
     * @param path
     * @return
     * @throws Exception
     */
    public static String readFile(String path) throws Exception {
        FileReader fReader = new FileReader(path);
        BufferedReader reader = new BufferedReader(fReader);
        StringBuilder sb = new StringBuilder();
        try {
            String str = null;
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
        } finally {
            if (reader != null)
                reader.close();
        }
        return sb.toString();
    }
}
